package com.uduemc.biso.web.component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.feign.HostFeign;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.web.details.CustomerUserDetails;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private HostFeign hostFeign;

	@Autowired
	private NodeFunction nodeFunction;

	@Autowired
	private ObjectMapper objectMapper;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		logger.info("登录成功执行的动作");

		/**
		 * 有且只有一个 host 则直接跳转至次控端
		 */
		CustomerUserDetails principal = (CustomerUserDetails) SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		RestResult restResult = hostFeign.findOkByUserId(principal.getCustomerUser().getId());
		if (restResult.getCode() != 200 || restResult.getData() == null) {
			logger.error(
					"hostFeign.findOkByUserId(principal.getCustomerUser().getId()); principal.getCustomerUser().getId(): "
							+ principal.getCustomerUser().getId()
							+ " restResult.getCode() != 200 || restResult.getData() == null");
			response.sendRedirect("/manage/");
		}
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, Host.class);
		@SuppressWarnings("unchecked")
		List<Host> list = (List<Host>) objectMapper.readValue(objectMapper.writeValueAsString(restResult.getData()),
				javaType);
		if (list.size() == 1) {
			Host host = list.get(0);
			// 制作次控端的url跳转至次控端
			String url = nodeFunction.getRedirectNodeUri(principal.getCustomerUser().getId(), host, "customerUser");
			logger.info(url);
			if (url != null) {
				response.sendRedirect(url);
				return;
			}
		}

		response.sendRedirect("/manage/");
	}

}
